import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Tag, 
  Space, 
  Button,
  message,
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Drawer,
  Descriptions,
  Row,
  Col
} from 'antd';
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons';
import request from '../../utils/request';
import * as XLSX from 'xlsx';
import moment from 'moment';
import './index.less';
import useAuthStore from '../../stores/authStore';

const { RangePicker } = DatePicker;

const Appointments = () => {
  const [loading, setLoading] = useState(false);
  const [appointments, setAppointments] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [detailVisible, setDetailVisible] = useState(false);
  const [currentAppointment, setCurrentAppointment] = useState(null);
  const [form] = Form.useForm();
  const { user } = useAuthStore();

  // 预约状态映射
  const statusMap = {
    upcoming: { text: '待上课', color: 'warning' },
    completed: { text: '已完成', color: 'success' },
    cancelled: { text: '已取消', color: 'error' },
    ongoing: { text: '进行中', color: 'processing' },
    refunded: { text: '已取消', color: 'error' }
  };

  // 获取预约列表
  const fetchAppointments = async (params = {}) => {
    try {
      if (!user?.id) {
        message.error('未获取到教师信息');
        return;
      }
      setLoading(true);
      const res = await request.get('/api/admin/appointments', { 
        params: {
          ...params,
          teacherId: user.id
        }
      });
      if (res.code === 0) {
        setAppointments(res.data);
      }
    } catch (error) {
      message.error('获取预约列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理搜索
  const handleSearch = (values) => {
    // 移除所有未定义的值
    const cleanParams = {};
    
    if (values.keyword) {
      cleanParams.keyword = values.keyword;
    }
    
    if (values.status) {
      cleanParams.status = values.status;
    }
    
    if (values.dateRange) {
      cleanParams.startDate = values.dateRange[0].format('YYYY-MM-DD');
      cleanParams.endDate = values.dateRange[1].format('YYYY-MM-DD');
    }
    
    fetchAppointments(cleanParams);
  };

  // 处理状态更新
  const handleStatusUpdate = (ids, status) => {
    Modal.confirm({
      title: '确认操作',
      content: `确定要将选中的预约状态更新为"${statusMap[status].text}"吗？`,
      onOk: async () => {
        try {
          const res = await request.put('/api/admin/appointments/batch-status', { 
            ids: Array.isArray(ids) ? ids : [ids], 
            status,
            teacherId: user.id
          });
          if (res.code === 0) {
            message.success('状态更新成功');
            fetchAppointments(form.getFieldsValue());
            setSelectedRows([]);
          }
        } catch (error) {
          message.error('状态更新失败');
        }
      }
    });
  };

  // 查看详情
  const handleViewDetail = (record) => {
    setCurrentAppointment(record);
    setDetailVisible(true);
  };

  // 导出数据
  const handleExport = () => {
    const data = appointments.map(item => ({
      '预约编号': item.id,
      '课程名称': item.course_title,
      '联系人': item.contact_name,
      '联系电话': item.contact_phone,
      '预约日期': item.booking_date,
      '时间段': item.time_slot,
      '预约状态': statusMap[item.status]?.text,
      '备注': item.remark,
      '创建时间': item.created_at
    }));

    const ws = XLSX.utils.json_to_sheet(data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '预约列表');
    XLSX.writeFile(wb, `预约列表_${moment().format('YYYY-MM-DD')}.xlsx`);
  };

  // 表格列配置
  const columns = [
    {
      title: '预约编号',
      dataIndex: 'id',
      width: 100,
    },
    {
      title: '课程名称',
      dataIndex: 'course_title',
      width: 200,
    },
    {
      title: '联系人',
      dataIndex: 'contact_name',
      width: 120,
    },
    {
      title: '联系电话',
      dataIndex: 'contact_phone',
      width: 150,
    },
    {
      title: '预约日期',
      dataIndex: 'booking_date',
      width: 120,
    },
    {
      title: '时间段',
      dataIndex: 'time_slot',
      width: 120,
    },
    {
      title: '预约状态',
      dataIndex: 'status',
      width: 120,
      render: (status) => (
        <Tag color={statusMap[status]?.color}>
          {statusMap[status]?.text}
        </Tag>
      )
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 200,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 180,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="default"
            onClick={() => handleViewDetail(record)}
          >
            详情
          </Button>
          {record.status === 'upcoming' && (
            <>
              <Button
                type="primary"
                size="small"
                onClick={() => handleStatusUpdate(record.id, 'completed')}
              >
                完成
              </Button>
              <Button
                danger
                size="small"
                onClick={() => handleStatusUpdate(record.id, 'cancelled')}
              >
                取消
              </Button>
            </>
          )}
        </Space>
      )
    }
  ];

  useEffect(() => {
    if (user?.id) {
      fetchAppointments();
    }
  }, [user]);

  return (
    <Card title="预约管理" className="appointment-page">
      {/* 搜索表单 */}
      <Form
        form={form}
        layout="inline"
        onFinish={handleSearch}
        className="search-form"
      >
        <Row gutter={24} style={{ width: '100%' }}>
          <Col span={6}>
            <Form.Item name="keyword">
              <Input
                placeholder="搜索课程名称/联系人"
                prefix={<SearchOutlined />}
              />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="status">
              <Select placeholder="预约状态" allowClear>
                {Object.entries(statusMap).map(([key, { text }]) => (
                  <Select.Option key={key} value={key}>
                    {text}
                  </Select.Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col span={8}>
            <Form.Item name="dateRange">
              <RangePicker placeholder={['开始时间', '结束时间']} />
            </Form.Item>
          </Col>
          <Col span={4}>
            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit">
                  搜索
                </Button>
                <Button onClick={() => {
                  form.resetFields();
                  fetchAppointments();
                }}>
                  重置
                </Button>
              </Space>
            </Form.Item>
          </Col>
        </Row>
      </Form>

      {/* 批量操作和导出按钮 */}
      <div className="operation-bar">
        <Space>
          {selectedRows.length > 0 && (
            <>
              <Button
                type="primary"
                onClick={() => handleStatusUpdate(selectedRows.map(r => r.id), 'completed')}
              >
                批量完成
              </Button>
              <Button
                danger
                onClick={() => handleStatusUpdate(selectedRows.map(r => r.id), 'cancelled')}
              >
                批量取消
              </Button>
            </>
          )}
          <Button
            type="primary"
            icon={<DownloadOutlined />}
            onClick={handleExport}
          >
            导出数据
          </Button>
        </Space>
      </div>

      {/* 预约列表 */}
      <Table
        className="appointment-table"
        columns={columns.map(col => ({
          ...col,
          ...(col.dataIndex === 'status' && {
            render: (status) => (
              <Tag color={statusMap[status]?.color} className="status-tag">
                {statusMap[status]?.text}
              </Tag>
            )
          }),
          ...(col.key === 'action' && {
            className: 'action-column'
          })
        }))}
        dataSource={appointments}
        rowKey="id"
        loading={loading}
        scroll={{ x: 1500 }}
        pagination={{
          pageSize: 10,
          showTotal: (total) => `共 ${total} 条`,
          showQuickJumper: true,
          showSizeChanger: false
        }}
        rowSelection={{
          selectedRowKeys: selectedRows.map(r => r.id),
          onChange: (_, rows) => setSelectedRows(rows)
        }}
      />

      {/* 详情抽屉 */}
      <Drawer
        title="预约详情"
        placement="right"
        width={600}
        onClose={() => setDetailVisible(false)}
        open={detailVisible}
        className="detail-drawer"
      >
        {currentAppointment && (
          <Descriptions column={1}>
            <Descriptions.Item label="预约编号">{currentAppointment.id}</Descriptions.Item>
            <Descriptions.Item label="课程名称">{currentAppointment.course_title}</Descriptions.Item>
            <Descriptions.Item label="联系人">{currentAppointment.contact_name}</Descriptions.Item>
            <Descriptions.Item label="联系电话">{currentAppointment.contact_phone}</Descriptions.Item>
            <Descriptions.Item label="预约日期">{currentAppointment.booking_date}</Descriptions.Item>
            <Descriptions.Item label="时间段">{currentAppointment.time_slot}</Descriptions.Item>
            <Descriptions.Item label="预约状态">
              <Tag color={statusMap[currentAppointment.status]?.color}>
                {statusMap[currentAppointment.status]?.text}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="备注">{currentAppointment.remark}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{currentAppointment.created_at}</Descriptions.Item>
            <Descriptions.Item label="是否已评价">
              {currentAppointment.is_rated ? '是' : '否'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Drawer>
    </Card>
  );
};

export default Appointments; 